﻿using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TcpClientTs.Common
{
    // 后台服务类
    public class TcpClientBackgroundService : BackgroundService
    {
        private readonly ILogger<TcpClientBackgroundService> _logger;

        public TcpClientBackgroundService(ILogger<TcpClientBackgroundService> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var tcpClient = new TouchSocket.Sockets.TcpClient();
            tcpClient.Connecting = (client, e) => EasyTask.CompletedTask;
            tcpClient.Connected = (client, e) => EasyTask.CompletedTask;
            tcpClient.Closing = (client, e) => EasyTask.CompletedTask;
            tcpClient.Closed = (client, e) => EasyTask.CompletedTask;

            await tcpClient.SetupAsync(new TouchSocketConfig()
                .SetRemoteIPHost("127.0.0.1:1024")
                .ConfigureContainer(a => a.AddConsoleLogger()));

            await tcpClient.ConnectAsync();
            _logger.LogInformation("TCP 客户端成功连接");

            using (var receiver = tcpClient.CreateReceiver())
            {
                while (!stoppingToken.IsCancellationRequested) // 使用 stoppingToken 安全退出
                {
                    try
                    {
                        using (var receiverResult = await receiver.ReadAsync(stoppingToken))
                        {
                            if (receiverResult.IsCompleted)
                            {
                                _logger.LogInformation($"客户端已断开，信息：{receiverResult.Message}");
                                break;
                            }

                            var mes = receiverResult.ByteBlock.ToString();
                            _logger.LogInformation($"客户端接收到信息：{mes}");
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // 正常退出
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "TCP 接收异常");
                        await Task.Delay(1000, stoppingToken); // 防止频繁重试
                    }
                }
            }

            //await tcpClient.DisconnectAsync();
            _logger.LogInformation("TCP 客户端已关闭");
        }
    }
}
